package com.example.malltest.product.service.impl;



import com.example.malltest.common.ServiceCode;
import com.example.malltest.common.ServiceException;
import com.example.malltest.product.entity.Product;
import com.example.malltest.product.entity.ProductDTO;
import com.example.malltest.product.entity.ProductDTO1;
import com.example.malltest.product.mapper.ProductMapper;
import com.example.malltest.product.service.ProductService;
import oracle.jrockit.jfr.openmbean.ProducerDescriptorType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ProductServiceImpl implements ProductService {


    @Autowired
    private ProductMapper productMapper;

    /**
     * 获取列表
     */
    @Override
    public List<Product> getList() {
        List<Product> products = productMapper.getList();
        if (products == null) {
            throw new ServiceException(ServiceCode.ERR_EXISTS, "不存在商品");
        }
        return products;
    }

    /**
     * 增加商品
     *
     * @param productDTO
     */
    @Override
    public void add(ProductDTO productDTO) {
        Product product = new Product();
        product.setName(productDTO.getName());
        product.setPrice(productDTO.getPrice());
        product.setNumber(productDTO.getNumber());
        product.setStatus(productDTO.getStatus());
        product.setUploadTime(productDTO.getUploadTime());
        int result = productMapper.save(product);
        if (result < 0) {
            throw new ServiceException(ServiceCode.ERR_FILE_UPLOAD, "更新失败！");
        }
    }

    /**
     * 删除商品
     *
     * @param id
     */
    @Override
    public void delete(Integer id) {
        Product product = productMapper.getById(id);
        if (product == null) {
            throw new ServiceException(ServiceCode.ERR_EXISTS, "不存在该商品！");

        }
        if (product.getStatus().equals("上架")) {
            throw new ServiceException(ServiceCode.ERR_SAVE_FAILED, "该商品上架中，无法删除！");
        }
        int result = productMapper.delete(id);
        if (result < 0) {
            throw new ServiceException(ServiceCode.ERR_FILE_UPLOAD, "更新失败！");
        }
    }

    /**
     * 编辑商品
     *
     * @param id
     * @param productDTO1
     */
    @Override
    public void edit(Integer id, ProductDTO1 productDTO1) {
        Product product = productMapper.getById(id);
        if (product == null) {
            throw new ServiceException(ServiceCode.ERR_EXISTS, "不存在该商品！");

        }
        product.setName(productDTO1.getName());
        product.setPrice(productDTO1.getPrice());
        product.setNumber(productDTO1.getNumber());
        product.setStatus(product.getStatus());
        product.setUploadTime(productDTO1.getUploadTime());
        int result = productMapper.edit(product);
        if (result < 0) {
            throw new ServiceException(ServiceCode.ERR_FILE_UPLOAD, "更新失败！");
        }
    }

    /**
     * 更改状态
     *
     * @param id
     * @param status
     */
    @Override
    public void status(Integer id, String status) {
        Product product = productMapper.getById(id);
        if (product == null) {
            throw new ServiceException(ServiceCode.ERR_EXISTS, "不存在该商品！");

        }
        product.setStatus(status);
        int result = productMapper.edit(product);
        if (result < 0) {
            throw new ServiceException(ServiceCode.ERR_FILE_UPLOAD, "更新失败！");
        }
    }

    /**
     * 上传图片
     *
     * @param id
     * @param image
     */
    @Override
    public void image(Integer id, MultipartFile image) {
        String uploadDirectory = "D:/vue-program/Electronics-Mall/mall/public/image/product";

        try {
            if (image.isEmpty()) {
                throw new ServiceException(ServiceCode.ERR_BAD_REQUEST, "请选择一个非空文件。");
            }

            // 创建上传目录，如果不存在
            Path uploadPath = Paths.get(uploadDirectory);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }

            // 文件存储
            String fileName = id + "_" + image.getOriginalFilename();
            Path targetPath = uploadPath.resolve(fileName);
            Files.copy(image.getInputStream(), targetPath, StandardCopyOption.REPLACE_EXISTING);

            // 保存地址
            Product product = productMapper.getById(id);
            product.setImage(targetPath.toString());
            int result = productMapper.edit(product);
            if (result <= 0) {
                throw new ServiceException(ServiceCode.ERR_SAVE_FAILED, "保存失败！");
            }
        } catch (Exception e) {
            throw new ServiceException(ServiceCode.ERR_SAVE_FAILED, "文件上传失败 - " + e.getMessage());
        }
    }

    /**
     * 热销商品
     *
     * @return
     */
    @Override
    public List<Product> getList1() {
        List<Product> products = productMapper.getList();
        if (products == null) {
            throw new ServiceException(ServiceCode.ERR_EXISTS, "不存在商品");
        }
        //排序
        List<Product> top3Products = products.stream()
                //降序排序
                .sorted(Comparator.comparing(Product::getNumber).reversed())
                .limit(3)
                .collect(Collectors.toList());

        return top3Products;
    }
    /**
     * 待补商品
     */
    @Override
    public List<Product> getList2() {
        List<Product> products = productMapper.getList();
        if (products == null) {
            throw new ServiceException(ServiceCode.ERR_EXISTS, "不存在商品");
        }
        List<Product> productsWithNumberLE10 = products.stream()
                .filter(product -> product.getNumber() <= 10)
                .collect(Collectors.toList());

        return productsWithNumberLE10;
    }

    /**
     * 查询商品
     * @param id
     * @return
     */
    @Override
    public Product search(Integer id){
        Product product = productMapper.getById(id);
        if (product == null) {
            throw new ServiceException(ServiceCode.ERR_EXISTS, "不存在该商品！");

        }
        return product;
    }
}
